/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package prototype.communication;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Server
 */
public class Client {

    private int timeout = 10000;
    private ConnectionResource cr;
    private Caster caster;
    private Receiver receiver;
    private Socket socket;

    public Client(ConnectionResource cr) {
        this.cr = cr;
    }

    public void connect() throws SocketTimeoutException {
        SocketAddress socketAddr = null;
        socket = new Socket();
        try {
            socketAddr = new InetSocketAddress(
                    InetAddress.getByName(cr.getHostname()),
                    cr.getPortNo());

            socket.connect(socketAddr, timeout);

            caster = new Caster(socket.getOutputStream());
            receiver = new Receiver(socket.getInputStream());
            Thread th = new Thread(receiver);
            th.start();
        } catch (SocketTimeoutException ex) {
            throw ex;
        } catch (UnknownHostException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void close() {
        try {
            if (receiver != null) {
                receiver.stopReceiving();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Caster getCaster() {
        return caster;
    }

    public Receiver getReceiver() {
        return receiver;
    }
}
